console.log("sTaoBao.js");

var resultStr = "";
var totalCount = 0;
var curCount = 0;
/**
 * 接收消息
 */
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.type) {
        case "background_getTaoBaoGoods":
            sendResponse({farewell: "success"});
            getTaoBaoGoods();
            break;
        case "background_getTaoBaoAllianceGoods":
            sendResponse({farewell: "success"});
            getTaoBaoAllianceGoods();
            break;
    }
});

function getTaoBaoAllianceGoods() {
    console.log("getTaoBaoAllianceGoods");
    curCount = 0;

    var goodsDiv = document.getElementsByClassName("color-m");

    for (var i = 0; i < goodsDiv.length; i++) {
        var div = goodsDiv[i];
        var link = div.href;
        if (link.indexOf("click") == -1) {

            resultStr += link;
            resultStr += "\n";
            curCount++;
            totalCount++;
        }
    }

    copyTextToClipboard(resultStr);

    alert("已经复制到粘贴板\n本次复制"+curCount+"件\  总共有"+totalCount+"件\n刷新页面清空所有商品");

}

function getTaoBaoGoods() {
    console.log("getTaoBaoGoods");
    curCount = 0;

    var goodsDiv = document.getElementsByClassName("item J_MouserOnverReq");

    for (var i = 0; i < goodsDiv.length; i++) {
        var div = goodsDiv[i];
        var link = div.getElementsByClassName("J_ClickStat")[1].href;
        if (link.indexOf("click") == -1) {

            resultStr += link;
            resultStr += "\n";
            curCount++;
            totalCount++;
        }
    }

    copyTextToClipboard(resultStr);

    alert("已经复制到粘贴板\n本次复制"+curCount+"件\  总共有"+totalCount+"件\n刷新页面清空所有商品");

}


function copyTextToClipboard(text) {
    var copyFrom = document.createElement("textarea");
    copyFrom.textContent = text;
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    body.removeChild(copyFrom);
}
